<--- %%NOBANNER%% --> varname.sas
 BackForward

/*-------------------<-- Start of Description-->---------------------\
| Retrieve the column names from a dataset;                          |
|---------------------<-- End of Description-->----------------------|
|--------------------------------------------------------------------|
|------------<-- Start of Files or Arguments Needed-->---------------|
| arguments:                                                         |
|    indata= the name of a data set you want to explore;             |
|    which= the 1st, 2nd or which variable do you want;              |
|    return=T/OUTPUT - return the name as a text string wihtout any  |
|                 single or double quotes;                           |
|            F/LOG - write the name in log window;                   |
|           both - write the name in log window and return the name; |
|           default - both;                                          |
|-------------<-- End of Files or Arguments Needed-->----------------|
|--------------------------------------------------------------------|
|------------------<-- Start of Files Created-->---------------------|
| Example: %varname(one, 1); / %varname(one, 1);                     |
| Usage:   %varname(indata,which);                                   |
\-------------------<-- End of Files Created-->---------------------*/
%macro varname(indata,which);
/*--------------------------------------------\
| Author:   Duo Zhou;                         |
| Created:  3-3-2001 11:27pm;                 |
| Modified: 8-30-2001 9:24pm;                 |
| Purpose:  Return the ith variable name in   |
|           the dataset;                      |
\--------------------------------------------*/
%local _varnamedsid_ _varnamerc_;
%let _varnamedsid_=%sysfunc(open(&indata));
%if &_varnamedsid_ %then %do;
   %if (%length(&which)>0) %then %do;
      %if (&which le %sysfunc(attrn(&_varnamedsid_,NVARS))) %then %sysfunc(varname(&_varnamedsid_,&which)); 
      %else %quote( );
   %end;
   %let _varnamerc_=%sysfunc(close(&_varnamedsid_));
%end;
%else %put ==> Alert! Open data set %data(&indata) failed.;
%mend varname;